//app.js
const qiniu = require("/utils/qiniu.min.js");
const mtjwxsdk = require('./utils/mtj-wx-sdk.js');
if (!Array.prototype.findIndex) {
  require('./utils/array-findIndex')
}
// var ald = require('./utils/ald-stat.js');
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
    

    
  },
  onShow:function(){
    //  向后台传递数据
    this.sendCode()  
    // console.log('json中每多长时间发生一次')
  },
  redirectIfNotPermit: function() {
    console.log('执行次数',1111)
    wx.getSetting({
      success: (res) => {
        wx.navigateTo({
          url: "/pages/noauth/noauth"
        })
      }
    })
  },
  redirectIfNotPermit1: function () {
        wx.navigateTo({
          url: "/pages/noauth/noauth?phone=0"
        })
  },
  //检测是否更新
  update(){
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
  },
  getUserInfo: function(cb) {
    // 暂时禁用更新检测
    // this.update();
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo);
    } 
    else {
      //调用登录接口
      wx.login({
        // fail: function(res) {
        //   that.redirectIfNotPermit();
        // },
        success: function(res) {
          var userCode = res.code
          //   uid = wx.getStorageSync('uid');
          // var phone = wx.getStorageSync('phone');
          // if (userCode && (uid == undefined || uid == '')) {
          //   console.log('检测',1111)
          //   that.redirectIfNotPermit();
          // } else if (phone == undefined || phone == ''){
          //   that.redirectIfNotPermit1();
          // } else{
            that.req({
              url: 'wechat/user/getUserInformation',
              method: 'POST',
              success: function(res) {
                that.globalData.userInfo = res.data;
                typeof cb == "function" && cb(that.globalData.userInfo);
              }
            });
          // }
        }
      })
    }
  },

  personalData:function(e){
    var that = this;
    that.req({
      url: 'wechat/user/getUserInformation',
      method: 'POST',
      success: function (res) {
        that.globalData.userInfo = res.data;
        typeof cb == "function" && cb(that.globalData.userInfo);
      }
    });
  },

  req: function(cfg) {
    var that = this, url = this.globalData.url + cfg.url;
    if(cfg.showLoad){
      wx.showLoading({
        title: cfg.loadMsg || '加载中',
        mask: true
      })
    }
    if (url.indexOf('?') >= 0){
      url += '&'
    }else{
      url += '?'
    }
    // 
    url = url + 'uid=' + wx.getStorageSync('uid') ;
    wx.request({
      url: cfg.purl ? cfg.purl : url,
      data: cfg.data,
      method: cfg.method ? cfg.method : 'GET',
      header: {
        'api-client': '8693ece21a2711ea995200163e05ff66',
        'api-version': '1.3.8',
      },
      success: function(res) {
        if (cfg.showLoad) {
          wx.hideLoading();
        }
        if (res && res.statusCode == 200) {
          cfg.success(res.data);
        } else {
          that.showToast({
            title: '网络出错，请确认网络或稍后使用',
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function(a) {
        if (cfg.showLoad) {
          wx.hideLoading();
        }
        that.showToast({
          title: '网络出错，请确认网络或稍后使用',
          icon: "none"
        })
      },                        
      complete: function() {
        wx.stopPullDownRefresh();
      }
    });
  },
  getNameByIdLabel(id, arr) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].children.length; j++) {
        var arrChild = arr[i].children[j];
        if (arrChild.id == id) {
          return arrChild.text.trim();
        }
      }
    }
    return '';
  },
  uploadToQiNiu: function (config) {
    var that = this;
    // 交给七牛上传
    that.getQiNiuToken(function (data) {
      qiniu.upload(config.filePath, config.success, config.error ? config.error : function (r) { }, {
        uploadURL: 'https://upload.qiniup.com',
        region: 'ECN',
        domain: data.qiniuDomain,
        uptoken: data.upToken,
      })
    });


  },
  //获取七牛云上传授权
  getQiNiuToken(fun) {
    this.req({
      url: 'wechat/image/uploadApplication',
      data: {},
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          typeof fun == "function" && fun(res.data);
        } else {
          wx.showToast({
            title: '获取文件上传权限失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  showToast: function(cfg) {
    wx.showToast(cfg);
  },
  globalData: {
    //是否显示签到、管理员等信息
    showMore: false,
    //是否显示银行卡等信息
    bankCard: true,
    userInfo: null,
    // 测试 
    activityMiniAppId: 'wxa0535d31b27c14d8',
    blessingAppId:'wx5388911760d25547',
    activityMiniEnvVersion: 'trial',
    url: 'https://test.yiqilaiwang.com/',
    showUrl: 'https://test.yiqilaiwang.com/',
    // 正式
    // activityMiniAppId: 'wx7bbb41f1149a2efa',
    // blessingAppId: 'wx389cd2531675cd84',
    // activityMiniEnvVersion: 'release',
    // url: 'https://www.yiqilaiwang.com/',
    // // url: 'https://demo.yiqilaiwang.com/',
    // showUrl: 'https://www.yiqilaiwang.com/',
  },



  // 小程序埋点检测
  // var now = new Date();
  // var newTime = now.toLocaleString();

  TestBuriedPoint: function (pointType1, pointType2){
    console.log(1)
    var newTime = Date.parse(new Date());   
    var data = {
      'pointType': pointType1,
      'createTime': newTime
    }
    if (pointType2){
      var data2 = {
        'pointType': pointType2,
        'createTime': newTime
      }
    }
    var arr = [] 
    var value = wx.getStorageSync('pointMsg')
    if (!value) {
      arr.push(data)
      if (pointType2){
        arr.push(data2)
      }
      // console.log(1111111)
      // console.log((arr))
      wx.setStorage({
        key: 'pointMsg',
        data: arr
      })
    } else {
      wx.getStorage({
        key: 'pointMsg',
        success: function (res) {
          // console.log(22222222222222)
          arr = res.data
          arr.push(data) 
          if (pointType2) {arr.push(data2)}        
          // console.log((arr))
          wx.setStorage({
            key: 'pointMsg',
            data: arr
          })
        }
      }) 
    }       
  },

  TestBuriedPoint2: function (pointType) {
    var newTime = Date.parse(new Date());
    var arr = []
    var value = wx.getStorageSync('pointMsg')
    var newpointType = (pointType).split(",")
    console.log(newpointType)
    console.log( typeof newpointType)
    if (!value) {
      newpointType.forEach((item,index)=>{
        arr.push({
          'pointType': item,
          'createTime': newTime})
      })
      console.log(1111111)
      console.log((arr))
      wx.setStorage({
        key: 'pointMsg',
        data: arr
      })
    } else {
      wx.getStorage({
        key: 'pointMsg',
        success: function (res) {
          console.log(22222222222222)
          arr = res.data
          newpointType.forEach((item, index) => {
            arr.push({
              'pointType': item,
              'createTime': newTime
            })
          })
          // console.log((arr))
          wx.setStorage({
            key: 'pointMsg',
            data: arr
          })
        }
      })
    }
  },
  //定时器
  sendCode: function (e) {
    var that = this;
    var newTime = Date.parse(new Date());
    var arr = []
    wx.getStorage({
      key: 'pointMsg',
      success: function (res) {
          arr = res.data
        // console.log('买点数组',arr,res.data)
                    wx.removeStorage({
                        key: 'pointMsg',
                        success: function (res) { },
                      })
        // console.log('时间差：'+ (newTime - res.data[0].createTime))
        // if (newTime - res.data[0].createTime >= 0*60*60*1000){
        if(arr.length >=50){
          // console.log('当前时间比第一次埋点时间大于24小时，向后台发送埋点数据，同时清空缓存')
          var uid = '';
          that.req({
            url: "wechat/user/getUserInformation",
            method: "post",
            data: {},
            success: function (res) {
              if (200 == res.code) {
                uid = res.data.id
                // console.log('我是现在的uid：',uid)
                    //检测新用户首页uv
                var newUvGroup = [
                  {
                    "pv": "yqlw_welcome_pv",
                    "uv": "yqlw_welcome_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_list_pv",
                    "uv": "yqlw_list_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_active_pv",
                    "uv": "yqlw_active_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_preview_pv",
                    "uv": "yqlw_preview_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_details_pv",
                    "uv": "yqlw_details_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_wallet_pv",
                    "uv": "yqlw_tabb_wallet_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_data_pv",
                    "uv": "yqlw_tabb_data_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_homepage_pv",
                    "uv": "yqlw_tabb_homepage_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_feedback_pv",
                    "uv": "yqlw_tabb_feedback_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_fboutus_pv",
                    "uv": "yqlw_tabb_fboutus_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_invitation_pv",
                    "uv": "yqlw_invitation_uv",
                    "amount": 0,
                  }, {
                    "pv": "yqlw_tabb_aboutus_pv",
                    "uv": "yqlw_tabb_aboutus_uv",
                    "amount": 0,
                  },

                ]
                arr.forEach((item,index)=>{
                  if (item.pointType == newUvGroup[0].pv){
                    newUvGroup[0].amount = 1
                  } else if (item.pointType == newUvGroup[1].pv) {
                    newUvGroup[1].amount = 1
                  } else if (item.pointType == newUvGroup[2].pv) {
                    newUvGroup[2].amount = 1
                  } else if (item.pointType == newUvGroup[3].pv) {
                    newUvGroup[3].amount = 1
                  } else if (item.pointType == newUvGroup[4].pv) {
                    newUvGroup[4].amount = 1
                  } else if (item.pointType == newUvGroup[5].pv) {
                    newUvGroup[5].amount = 1
                  } else if (item.pointType == newUvGroup[6].pv) {
                    newUvGroup[6].amount = 1
                  } else if (item.pointType == newUvGroup[7].pv) {
                    newUvGroup[7].amount = 1
                  } else if (item.pointType == newUvGroup[8].pv) {
                    newUvGroup[8].amount = 1
                  } else if (item.pointType == newUvGroup[9].pv) {
                    newUvGroup[9].amount = 1
                  } else if (item.pointType == newUvGroup[10].pv) {
                    newUvGroup[10].amount = 1
                  } else if (item.pointType == newUvGroup[11].pv) {
                    newUvGroup[11].amount = 1
                  } 
                })
                newUvGroup.forEach((item,index)=>{
                  if(item.amount == 1){
                    arr.push({
                      'pointType': item.uv,
                      'createTime': newTime,
                      'userId': uid
                    }) 
                  }
                })
                    
                arr.forEach((item, index) => {
                  item.userId = uid
                })
                //提交数据到后台
                // that.req({
                //   url: 'wechat/dataBuryingPoint/insertInBatch',
                //   method: 'post',
                //   data: arr,
                //   success: function (res) {
                //     if (res.code == 200) {
                //       console.log('向后台发送数据成功')
                //       wx.removeStorage({
                //         key: 'pointMsg',
                //         success: function (res) { },
                //       })
                //     } else {
                      
                //     }
                //   },
                //   fail:function(err){
                //     console.log('埋点报错',err)
                //   }
                // })               
              } else {
              }
            }
          });

        }
        
      }
    }) 

    // var i = setInterval(function () {
    //   that.judgeUV()
    //   var arr = []

      
    // }, 86400000)
  },


});

/**
 * 定义克隆方法
 */
Object.defineProperty(
  Object.prototype,
  'clone', {
    value: function() {
      var cloneSelf = {};
      for (var key in this) {
        cloneSelf[key] = this[key];
      }
      return cloneSelf;
    },
    writable: false,
    enumerable: false,
    configurable: false
  });